package com.kefu.sys.service;

import cn.hutool.core.collection.CollUtil;
import cn.hutool.core.date.DateUtil;
import cn.hutool.core.util.IdUtil;
import cn.hutool.core.util.StrUtil;
import com.baomidou.mybatisplus.core.incrementer.DefaultIdentifierGenerator;
import com.baomidou.mybatisplus.core.toolkit.Wrappers;
import com.baomidou.mybatisplus.extension.plugins.pagination.Page;
import com.google.common.collect.Lists;
import com.kefu.boss.mapper.BossVersionMapper;
import com.kefu.boss.model.BossVersion;
import com.kefu.chat.mapper.ChatChannelMapper;
import com.kefu.chat.model.ChatChannel;
import com.kefu.common.context.KefuContext;
import com.kefu.common.service.AbstractKefuService;
import com.kefu.common.util.Assert;
import com.kefu.common.util.JacksonUtil;
import com.kefu.robot.mapper.RobotInfoMapper;
import com.kefu.robot.model.RobotInfo;
import com.kefu.sys.mapper.CdrRghistoryTenantMapper;
import com.kefu.sys.mapper.SysTenantMapper;
import com.kefu.sys.model.*;
import com.kefu.sys.vo.*;
import lombok.extern.slf4j.Slf4j;
import org.springframework.security.crypto.bcrypt.BCryptPasswordEncoder;
import org.springframework.stereotype.Service;
import org.springframework.transaction.annotation.Transactional;

import javax.annotation.Resource;
import java.util.ArrayList;
import java.util.List;

@Slf4j
@Service
public class SysTenantService extends AbstractKefuService<SysTenant> {
    @Resource
    private BossVersionMapper bossVersionMapper;
    @Resource
    protected SysUserService sysUserService;
    @Resource
    protected SysOrganService sysOrganService;
    @Resource
    protected RobotInfoMapper robotInfoMapper;
    @Resource
    protected SysTenantMapper sysTenantMapper;
    @Resource
    protected ChatChannelMapper chatChannelMapper;
    @Resource
    protected CdrRghistoryTenantMapper cdrRghistoryTenantMapper;
    @Resource
    protected SysRoleService sysRoleService;
    @Resource
    protected SysUserRoleService userRoleService;
    @Resource
    protected SysRoleMenuService sysRoleMenuService;

    DefaultIdentifierGenerator generator = new DefaultIdentifierGenerator();

    public void updateByBoss(SysTenantUpdateBossVo tenantVo) {
        log.info("1. 更新租户信息:{}", JacksonUtil.toString(tenantVo));
        SysTenant tenant = tenantVo.convert();
        log.info("2. 更新租户信息:{}", JacksonUtil.toString(tenant));
        super.update(tenant);
        cleanCache(tenant.getTenantId());
        String versionId = tenantVo.getVersionId();
        if (StrUtil.isNotBlank(versionId)) {
            BossVersion version = bossVersionMapper.selectByPrimaryKey(versionId);
            Assert.isNull(version, "更新的版本信息异常！");
            List<String> menuList = Lists.newArrayList(version.getVersionMenus().split(","));
            if (CollUtil.isNotEmpty(menuList)) {
                sysRoleMenuService.delete(Wrappers.lambdaQuery(SysRoleMenu.class).eq(SysRoleMenu::getRoleId,tenant.getTenantId()));
                List<SysRoleMenu> list = new ArrayList<>();
                for (String menuId : menuList) {
                    SysRoleMenu sysRoleMenu = new SysRoleMenu();
                    sysRoleMenu.setId(generator.nextId(sysRoleMenu));
                    sysRoleMenu.setMenuId(menuId);
                    sysRoleMenu.setRoleId(tenant.getTenantId());
                    sysRoleMenu.setTenantId(tenant.getTenantId());
                    list.add(sysRoleMenu);
                }
                sysRoleMenuService.save(list);
            }
        }
    }
    private void cleanCache(String tenantId) {
        redisTemplate.delete("kefu_client_cache::" + tenantId);
        redisTemplate.delete("sys_tenant::" + tenantId);
    }

    @Transactional
    public SysTenant tenantAdd(SysTenantInsertVo sysTenantVo) {
        String contactEmail = sysTenantVo.getContactEmail();
        long adminCount = sysUserService.count(Wrappers.lambdaQuery(SysUser.class).eq(SysUser::getUserEmail, contactEmail));
        Assert.isTrue(adminCount > 0, "管理员邮箱已存在！");
        String versionId = sysTenantVo.getVersionId();
        BossVersion version = bossVersionMapper.selectByPrimaryKey(versionId);
        Assert.isNull(version, "添加的版本信息异常!");
        long currentTimeMillis = System.currentTimeMillis();
        Assert.isTrue(currentTimeMillis > sysTenantVo.getExpireTime(), "租户过期时间不能小于当前时间！");
        SysTenant tenant = sysTenantVo.convert();
        tenant.setTenantId(IdUtil.simpleUUID());
        tenant.setCreateTime(currentTimeMillis);
        tenant.setTenantSecret(new BCryptPasswordEncoder().encode(sysTenantVo.getUserPwd()));
        tenant.setAppSecret(sysTenantVo.getUserPwd());
        super.save(tenant);
        logger.info("租户开通，添加租户信息:{}", JacksonUtil.toString(tenant));

        SysOrgan sysOrgan = new SysOrgan();
        sysOrgan.setId(IdUtil.simpleUUID());
        sysOrgan.setParentId("0");
        sysOrgan.setName("总公司");
        sysOrgan.setTenantId(tenant.getTenantId());
        sysOrgan.setWeight(1);
        sysOrgan.setCreateTime(currentTimeMillis);
        sysOrganService.save(sysOrgan);
        logger.info("租户开通，添加租户组织根节点信息:{}", JacksonUtil.toString(sysOrgan));

        SysUser sysUser = new SysUser();
        sysUser.setUserId(IdUtil.simpleUUID());
        sysUser.setTenantId(tenant.getTenantId());
        sysUser.setUserEmail(sysTenantVo.getContactEmail());
        sysUser.setUserName(sysTenantVo.getContactName());
        sysUser.setUserNick(sysUser.getUserName());
        sysUser.setUserPwd((new BCryptPasswordEncoder()).encode(sysTenantVo.getUserPwd()));
        sysUser.setUserPhone(sysTenantVo.getContactTel());
        sysUser.setUserPost(2);//超管
        sysUser.setCreateTime(currentTimeMillis);
        sysUser.setOrganId(sysOrgan.getId());
        sysUserService.save(sysUser);
        logger.info("租户开通，添加租户的超级管理员:{}", JacksonUtil.toString(sysUser));

        RobotInfo robotInfo = new RobotInfo();
        robotInfo.setId(IdUtil.simpleUUID());
        robotInfo.setTenantId(tenant.getTenantId());
        robotInfo.setRobotNo(1);
        robotInfo.setRobotName("机器人小助");
        robotInfo.setCreateTime(currentTimeMillis);
        robotInfoMapper.insert(robotInfo);
        logger.info("租户开通，添加租户默认机器人:{}", JacksonUtil.toString(robotInfo));

        ChatChannel channel = new ChatChannel();
        channel.setChannelId(IdUtil.simpleUUID());
        channel.setTenantId(tenant.getTenantId());
        channel.setChannelName("默认网站");
        channel.setChannelType(1);
        channel.setCreateTime(currentTimeMillis);
        chatChannelMapper.insert(channel);
        channel.setChannelId(IdUtil.simpleUUID());
        logger.info("租户开通，添加租户默认渠道:{}", JacksonUtil.toString(channel));

        SysRole role = new SysRole();
        role.setRoleName("默认管理员");
        role.setRoleDesc("系统默认");
        role.setRoleId(tenant.getTenantId());//默认角色id跟企业id一样
        role.setTenantId(tenant.getTenantId());
        role.setCreateTime(currentTimeMillis);
        role.setRoleType(0);
        sysRoleService.save(role);
        logger.info("租户开通，添加租户默认管理员:{}", JacksonUtil.toString(role));

        SysUserRole sysUserRole = new SysUserRole();
        sysUserRole.setId(generator.nextId(sysUserRole));
        sysUserRole.setUserId(sysUser.getUserId());
        sysUserRole.setRoleId(role.getRoleId());
        userRoleService.save(sysUserRole);
        logger.info("租户开通，添加用户管理员角色关联关系:{}", JacksonUtil.toString(sysUserRole));

        List<String> menuList = Lists.newArrayList(version.getVersionMenus().split(","));
        List<SysRoleMenu> list = new ArrayList<>();
        for (String menuId : menuList) {
            SysRoleMenu sysRoleMenu = new SysRoleMenu();
            sysRoleMenu.setId(generator.nextId(sysRoleMenu));
            sysRoleMenu.setMenuId(menuId);
            sysRoleMenu.setRoleId(role.getRoleId());
            sysRoleMenu.setTenantId(tenant.getTenantId());
            list.add(sysRoleMenu);
        }
        sysRoleMenuService.batchAdd(list);
        logger.info("租户开通，添加默认管理员菜单关联关系:{}", JacksonUtil.toString(list));
        return tenant;
    }

    public void deleteByTenantId(String id) {
        cleanCache(id); // 清除缓存
        sysTenantMapper.updateStatusById(id); // 更新状态为"停用"

    }

    public void recharge(SysTenantRechargeVo sysTenantVo) {

        // 常量-充值类型-2
        final int RECHARGE_TYPE = 2;
        // 新增账单记录

        // 查询当前机构的旧额度
        int beforeCount = sysTenantMapper.selectById(sysTenantVo.getTenantId()).getAvailableCallCount();

        // 机构的新额度
        int afterCount = sysTenantVo.getAvailableCallCount() + beforeCount;

        CdrRghistoryTenant cdrRghistoryTenant = new CdrRghistoryTenant();
        cdrRghistoryTenant.setTenantId(sysTenantVo.getTenantId());
        cdrRghistoryTenant.setRgmoney(String.valueOf(sysTenantVo.getAvailableCallCount()));
        cdrRghistoryTenant.setCreateTime(DateUtil.date());
        cdrRghistoryTenant.setType(RECHARGE_TYPE);
        cdrRghistoryTenant.setBeforemoney(String.valueOf(beforeCount));
        cdrRghistoryTenant.setAftermoney(String.valueOf(afterCount));
        cdrRghistoryTenant.setRgpeopel(KefuContext.getKefuContext().getUserName());

        cdrRghistoryTenantMapper.insert(cdrRghistoryTenant);
        // 更新企业记录
        log.info("充值企业记录:{}", JacksonUtil.toString(sysTenantVo));
        sysTenantMapper.recharge(sysTenantVo);
    }

    public String getVersionName(String tenantId) {
        return bossVersionMapper.selectVersionNameByTenantId(tenantId);
    }
}
